package com.Guo.system.service.impl;

import com.Guo.system.entity.Role;
import com.Guo.system.entity.User;
import com.Guo.system.mapper.RoleMapper;
import com.Guo.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Admin
 * @project UserDetailsServiceImpl
 * @description
 * @date 2020-12-23-11:16
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //需要构造出 org.springframework.security.core.userdetails.User 对象并返回
        //Granted允许 Authority权限  SimpleGrantedAuthority为GrantedAuthority的实现类
        System.out.println("用户名为："+s+"....");
        List<GrantedAuthority> authorities = new ArrayList<>();
        User user = userMapper.selectByName(s);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户%s不存在", s));
        } else {
            //根据请求路径获取用户权限，因为有可能有多个用户拥有同一权限
            List<Role> roles = roleMapper.selectListByUser(user.getId());
            for (Role role : roles) {
                //这里的条件是放 权限code  如create_user
                System.out.println(role.getRoleName());
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
                authorities.add(simpleGrantedAuthority);
            }
        }
//        String username：用户名
//        String password： 密码
//        boolean enabled： 账号是否可用
//        boolean accountNonExpired：账号是否过期  not_expired
//        boolean credentialsNonExpired：密码是否过期  credentials_not_expired
//        boolean accountNonLocked：账号是否锁定 account_not_locked
//        Collection<? extends GrantedAuthority> authorities)：用户权限列
// String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities
        return new org.springframework.security.core.userdetails.User
                (user.getUsername(), user.getPassword(), authorities);
    }
}
